# encoding: utf-8

import urllib
import re # I'm aware that XML is not regular, but this is a workaround for the fact that xml.dom.minidom does not import correctly on some installations of Python

def main(env):
	def dirtyParse(labels):
		pattern = "".join(ur'<%s data="(.*?)"/>' % label for label in labels)
		return [dict(zip(labels,match.groups())) for match in re.finditer(pattern,data.decode("utf8"))]
	
	text = env["context"]["selection"]
	queryDict = {
		"weather" : (text if text.strip() else env["prefs"]["cwWeather_defaultLocation"]).encode("utf8"),
		"hl" : env["constants"]["language"]
	}
	url = env["static"]["cwWeather_baseUrl"] + "/ig/api?" + urllib.urlencode(queryDict)
	data = urllib.urlopen(url).read().decode("latin1").encode("utf8")
	forecasts = dirtyParse(('day_of_week', 'low', 'high', 'icon', 'condition'))
	hereAndNow = dirtyParse(('city', 'postal_code', 'latitude_e6', 'longitude_e6', 'forecast_date', 'current_date_time', 'unit_system'))[0]
	hereAndNow.update(dirtyParse(('condition','temp_f', 'temp_c', 'humidity', 'icon', 'wind_condition'))[0])
	html = "".join([env["static"]["cwWeather_htmlDay"] % forecast for forecast in forecasts])
	html = env["static"]["cwWeather_htmlBody"].replace("<!-- DAYS -->",html) % hereAndNow
	html = env["static"]["cwWeather_htmlDoc"].replace("<!-- BODY -->",html)
	html = html.replace("/ig/images/weather/",env["static"]["cwWeather_baseUrl"]+"/ig/images/weather/")
	forecasts[0]["day_of_week"] = env["static"]["cwWeather_textEnumerate"] % env["static"]["cwWeather_textToday"]
	forecasts[1]["day_of_week"] = env["static"]["cwWeather_textEnumerate"] % env["static"]["cwWeather_textTomorrow"]
	forecasts[2]["day_of_week"] = env["static"]["cwWeather_textEnumerate"] % forecasts[2]["day_of_week"].title()
	forecasts[3]["day_of_week"] = env["static"]["cwWeather_textEnumerate"] % forecasts[3]["day_of_week"].title()
	text = env["static"]["cwWeather_textNow"] % hereAndNow + "".join(env["static"]["cwWeather_textDay"] % forecast for forecast in forecasts)
	(width,height) = env["static"]["cwWeather_size"].split("x")
	return [("htmlBox",{
			"text": text.replace("&#39;","'"),
			"html": html,
			"width": int(width),
			"height": int(height),
			"label": env["static"]["cwWeather_label"]
		}),
		("moveCursor",0)
	]

